#!/bin/bash
#
# 在 K8S 导入导出 Samba 镜像脚本，支持 Docker 和 containerd (ctr)
# 执行格式：./export_samba_image.sh samba latest

image_dir="/usr/local/src"

echo_log_info() {
    echo -e "$(date +'%F %T') - [Info] $*"
}
echo_log_warn() {
    echo -e "$(date +'%F %T') - [Warn] $*"
}
echo_log_error() {
    echo -e "$(date +'%F %T') - [Error] $*"
    exit 1
}

# 使用 Docker 导出镜像
export_image_docker() {
    echo_log_info "使用 Docker 导出镜像 \033[33m$image:$tag\033[0m"

    docker save -o "$image_tar_dir" "$image:$tag" &>/dev/null || echo_log_error "\033[31m镜像导出失败！\033[0m"
    echo_log_info "镜像导出完成: \033[33m$image_tar_dir\033[0m"
}

# 使用 Containerd 导出镜像
export_image_ctr() {
    echo_log_info "使用 Containerd 导出镜像 \033[33m$image:$tag\033[0m"

    ctr -n=k8s.io images export "$image_tar_dir" "$image:$tag" &>/dev/null || echo_log_error "\033[31m镜像导出失败！\033[0m"
    echo_log_info "镜像导出完成: \033[33m$image_tar_dir\033[0m"
}

main() {
    if [[ $# -ne 2 ]]; then
        echo_log_error "用法: $0 <镜像名> <标签>"
    elif command -v docker >/dev/null 2>&1; then
        runtime="docker"
    elif command -v ctr >/dev/null 2>&1; then
        runtime="containerd"
    else
        echo_log_error "未检测到docker或containerd容器运行时"
    fi

    echo_log_info "检测到运行时: $runtime"

    if ! crictl images | grep -q "$1" ; then
        echo_log_error "未找到镜像: $1"
    elif ! crictl images | grep "$1" | grep -q "$2"; then
        echo_log_error "未找到镜像标签: $2"
    fi

    image=$(crictl images | awk '{print $1}' | grep "$1" | head -n1)
    tag=$(crictl images | grep "$image.*$2" | awk '{print $2}')
    image_tar_dir="$image_dir/${image##*/}-$tag.tar"

    if [[ "$runtime" =~ docker ]]; then
        export_image_docker
    elif [[ "$runtime" =~ containerd ]]; then
        export_image_ctr
    fi
}

main "$@"